<template>
  <div>
    <el-button type="warning"  size="small" @click="doPrint" >打印</el-button>
    <el-button type="warning"  size="small" @click="doPdf" >导出pdf</el-button>
    <el-button type="warning"  size="small" @click="printOut('orderForm1')" >导出pdf</el-button>
    <div ref="orderForm1">
      <el-card class="print">
        <p id="title"></p>
        <el-table
          :data="tableData"
          border
          style="width: 100%">
          <el-table-column
            prop="date"
            label="日期"
            width="180"
            align='center'>
          </el-table-column>
          <el-table-column
            prop="name"
            label="姓名"
            width="180"
            align='center'>
          </el-table-column>
          <el-table-column
            prop="address"
            label="地址"
            align='center'>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
</div>
</template>

<script>
import html2canvas from "html2canvas";
import JsPDF from "jspdf"
export default {
  components:{
  },
  data(){
    return {
      value: new Date(),
      tableData: [{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1517 弄'
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1519 弄'
        }, {
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1516 弄'
        },{
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }]
    }
  },
  methods:{
    doPrint() {
      let subOutPrintButton = document.getElementsByClassName("print");
      var newContent = [];
      for (var i = 0; i < subOutPrintButton.length; i++) {
        var obj = subOutPrintButton[i].innerHTML;
        newContent.push(obj);
      }
      // 重新开启一个新窗口打印页面
      const _win = window.open('', '');
      _win.document.write(newContent);
      _win.document.body.innerHTML = newContent;
      _win.document.getElementsByTagName('body')[0].style.textAlign = "center";
      _win.document.getElementById("title").innerText = "出纳收款日报表"
      // 缩放比例 解决过大页面打印不全问题
      _win.document.getElementsByTagName('body')[0].style.zoom = 0.65;
      // 写页面样式
      _win.document.write('<style>  p{font-size:26px} .label{ display: flex;justify-content: space-between;} #title {padding:15px;font-size:40px} thead th{ border-left:1px solid #000;border-top:1px solid #000 } table{margin:0 auto;cellspacing:0;cellpadding:0; border-right:1px solid #000;border-bottom:1px solid #000} table td{border-left:1px solid #000;border-top:1px solid #000;text-align: center; } .cell{text-align: right!important; font-size:26px;} .is-center .cell{text-align:center!important; font-size:26px}</style>');
      _win.window.print();
      _win.window.close();  // 打印完成后关闭后新窗口
    },
    doPdf(){
      let _this = this
      let myBox = this.$refs.orderForm1; //获取ref里面的内容
      html2canvas(myBox, {
        useCORS: true, //是否尝试使用CORS从服务器加载图像
        allowTaint: true,
        dpi: 300, //解决生产图片模糊
        scale: 3, //清晰度--放大倍数
      }).then(function (canvas) {
        let contentWidth = canvas.width
        let contentHeight = canvas.height
        let pageHeight = contentWidth / 592.28 * 841.89 // 一页pdf显示html页面生成的canvas高度;
        let leftHeight = contentHeight //未生成pdf的html页面高度
        let position = 0 //pdf页面偏移
        //a4纸的尺寸[595.28,841.89]，html页面生成的canvas在pdf中图片的宽高
        // let imgWidth = 595.28
        let imgWidth = 560.28  //宽度
        let imgHeight = 592.28 / contentWidth * contentHeight
        let pageData = canvas.toDataURL('image/jpeg', 1.0)
        let PDF = new JsPDF('', 'pt', 'a4')

        // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度(841.89)
        //当内容未超过pdf一页显示的范围，无需分页
        if (leftHeight < pageHeight) {
          PDF.addImage(pageData, 'JPEG', 20, 20, imgWidth, imgHeight)
        } else {
          while (leftHeight > 0) {
            PDF.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
            leftHeight -= pageHeight
            position -= 841.89
            if (leftHeight > 0) {
              PDF.addPage()
            }
          }
        }
        PDF.save('食堂利用明细' + '.pdf')//下载标题
      });
    },
    printOut(DomName) {
      console.log("正在帮您导出......")
      //title，随意设置，也可以提出来做参数，传入进来，自己发挥
      var title = '测试啊';
      var that = this;
      var shareContent = DomName; //需要截图的包裹的（原生的）DOM 对象
      //打印看有没有获取到dom
      console.log(shareContent)
      var width = shareContent.offsetWidth; //获取dom 宽度
      var height = shareContent.offsetHeight; //获取dom 高度
      var canvas = document.createElement("canvas"); //创建一个canvas节点
      var scale = 2; //定义任意放大倍数 支持小数
      canvas.width = width * scale; //定义canvas 宽度 * 缩放，在此我是把canvas放大了2倍
      canvas.height = height * scale; //定义canvas高度 *缩放
      canvas.getContext("2d").scale(scale, scale); //获取context,设置scale
      html2canvas(DomName, {
      //允许跨域图片的加载
      useCORS: true,
      }).then(function (canvas) {
      var context = canvas.getContext("2d");
      // 【重要】关闭抗锯齿
      context.mozImageSmoothingEnabled = false;
      context.webkitImageSmoothingEnabled = false;
      context.msImageSmoothingEnabled = false;
      context.imageSmoothingEnabled = false;
      var imgData = canvas.toDataURL('image/', 1.0); //转化成base64格式,可上网了解此格式
      var img = new Image();
      img.src = imgData;
      img.onload = function () {
      img.width = img.width / 2; //因为在上面放大了2倍，生成image之后要/2
      img.height = img.height / 2;
      img.style.transform = "scale(0.5)";
      var doc = '';
      if (this.width > this.height) {
      //此可以根据打印的大小进行自动调节
      doc = new JsPDF("l", "mm", [
        this.width * 0.555,
        this.height * 0.555
        ]);
      } else {
      doc = new JsPDF("p", "mm", [
        this.width * 0.555,
        this.height * 0.555
        ]);
      }
      console.log(doc)
      doc.addImage(
        imgData,
        "jpeg",
        10,
        0,
        this.width * 0.505,
        this.height * 0.545
      );
        doc.save(title + "-文件.pdf");
        console.log("倒数3秒导出啦")
      };
      });
    }
  },
//   watch:{
//     selectedArr:{
//       handler(newval,oldval){
//         $("br").remove();
//         if(newval && newval.length !== 0 ){
//           this.handleShowData(newval)
//         }
//       },
//       deep: true,
//     },
    // checkData:{
    //   handler(newVal){
    //     if(newVal.length !== 0){
    //       this.checkShowData(newVal)
    //     }
    //     // console.log("newVal",newVal)
    //     // console.log(this.date)
    //   },
    //   deep:true
    // },
    // date:{
    //   handler(newVal){
    //     console.log(newVal)
        
    //   },
    //   deep:true
    // },
    
//   }
}
</script>

<style scoped>
*{
  font-size: 16px;
}
b{
  font-weight: bold;
}
thead{
  border-top: 1px solid #000;
  /* border-bottom: 1px solid #000; */
}
.center{
  text-align: center;
  margin: auto;
}
.right{
  text-align: right;
}
.text{
  border-bottom: 3px double black;
  font-size: 18px;
  font-weight: bold;
}
.between{
  display: flex;
  justify-content: space-between;
  margin: 10px auto;
}
.between p{
  flex: 1;
}
table{
  table-layout:fixed;
}
.info{
  width: 80%;
}
.table{
  margin-bottom: 20px;
}
tr{
  height: 30px;
  line-height: 30px;
  border-top: 1px solid black;
}
.top{margin-top: 10px}
@page{
  size: auto A4 landscape;
  margin: 15mm 13mm;
}
@media print{

}
</style>
